package com.cedifie.lendapp.ui.user.fm

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.cedifie.lendapp.BuildConfig
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.FmUserMenuBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.MvpFm
import com.cedifie.lendapp.ui.PaPoyAct
import com.cedifie.lendapp.ui.user.act.CedUserFeedbackAct
import com.cedifie.lendapp.ui.user.act.CedUserLoginAct
import com.cedifie.lendapp.ui.user.adapter.CedKefuContactAdapter
import com.cedifie.lendapp.ui.user.impl.CedUserPresenterImpl
import com.cedifie.lendapp.ui.user.view.ICedUserView
import com.cedifie.lendapp.utils.dialog.ClearDataDialog
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.helper.ScoreDialogHelper
import com.cedifie.lendapp.utils.helper.SharedHelper
import com.cedifie.lib_baseadapter.CEDOnItemChildClickListener
import com.lib.base.utils.TitleBarUtil
import com.lib.base.utils.log.LogHelper
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject


/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/17 13:45
 * @Annotation：个人中心
 */
class CedUserFm(): MvpFm<ICedUserView, CedUserPresenterImpl>(),ICedUserView {
    private var _binding: FmUserMenuBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )
    private var drawerLayout: DrawerLayout? = null

    //联系方式列表
    private var contactAdapter: CedKefuContactAdapter? = null

    constructor(drawerLayout: DrawerLayout): this(){
        this.drawerLayout = drawerLayout
    }

    override fun getCedRootView(inflater: LayoutInflater): View {
        _binding = FmUserMenuBinding.inflate(inflater)
        return binding.root
    }

    override fun initCedView() {
        rootViewBinding.containerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.transparent))
        _binding?.contentLayout?.setPadding(0,TitleBarUtil.getStatusBarHeight(),0,0)
        initCedRecyclerView()
        //默认不显示清除数据按钮
        _binding?.clearDataLayout?.visibility = View.GONE
        _binding?.tvClearData?.paint?.flags = Paint.UNDERLINE_TEXT_FLAG//下划线
        _binding?.tvClearData?.paint?.isAntiAlias = true//抗锯齿

        EventBus.getDefault().register(this)
    }

    override fun initCedListener() {
        //关闭
        _binding?.closeLayout?.setOnClickListener {
            drawerLayout?.closeDrawer(GravityCompat.START)
        }

        //我的账户
        _binding?.imageAvatar?.setOnClickListener {
//            _binding?.closeLayout.callOnClick()
//            Handler().postDelayed({
//                onIntent(UserAccountAct::class.java)
//            },300)
        }

        //意见反馈
        _binding?.feedbackLayout?.setOnClickListener {
            _binding?.closeLayout?.callOnClick()
            Handler(Looper.getMainLooper()).postDelayed({
                onIntent(CedUserFeedbackAct::class.java)
            },300)
        }

        //数据安全
        _binding?.dataPrivacyLayout?.setOnClickListener {
//            onIntent(UserDataPrivacyAct::class.java)
            onIntent(PaPoyAct::class.java)
        }

        //打分
        _binding?.rateUsLayout?.setOnClickListener {
            showCedLoading(getString(R.string.loading))
            mvpPresenter?.loadCedRateUsAction()
        }

        //退出登录
        _binding?.loginOutLayout?.setOnClickListener {
            _binding?.closeLayout?.callOnClick()
            HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_USER_LOGINOUT,"")
            //移除已登录状态
            SharedHelper.onCedLoginOut()
            Handler(Looper.getMainLooper()).postDelayed({
                onIntent(CedUserLoginAct::class.java)
            },300)
        }

        //清除数据
        _binding?.clearDataLayout?.setOnClickListener {
            showCedClearUserDataDialog()
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initCedData() {
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_USER_START,"")
        //手机号码
        val mobile = SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_MOBILE)
        //区号
        val timeZoneCode = SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_TIMEZONE_CODE)
        _binding?.textMobile?.text = "+$timeZoneCode  $mobile"

        //获取版本名称
        _binding?.textVersion?.text = String.format(getString(R.string.personal_version), BuildConfig.VERSION_NAME)

        //获取客服联系方式列表
        mvpPresenter?.loadCedContactListAction()
        //是否显示清除数据按钮
        mvpPresenter?.checkClearUserDataAction(true)
    }

    override fun createMvpPresenter(): CedUserPresenterImpl {
        return CedUserPresenterImpl(context)
    }

    /**
     * 初始化客服联系方式列表
     */
    private fun initCedRecyclerView() {
        _binding?.recyclerView?.setHasFixedSize(false)
        _binding?.recyclerView?.isNestedScrollingEnabled = false
        _binding?.recyclerView?.isFocusableInTouchMode = false //不需要焦点
        _binding?.recyclerView?.layoutManager = LinearLayoutManager(context)
        contactAdapter = CedKefuContactAdapter(_binding?.recyclerView)
        _binding?.recyclerView?.adapter = contactAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        contactAdapter?.setOnItemChildClickListener(CEDOnItemChildClickListener { parent, childView, position ->
            contactAdapter?.let {
                val item = it.getItem(position)
                when(childView.id){
                    R.id.btnCopy -> {//复制
                        mvpPresenter?.onCedCopyAction(item)
                    }
                    R.id.btnDial -> {//拨号
                        mvpPresenter?.onCedCallAction(item)
                    }
                }
            }
        })
    }

    /**
     * 客服工作时间
     */
    override fun showCedCustomerWorkTime(workTime: String) {
        //客服工作时间
        _binding?.textWorkTime?.text = String.format(getString(R.string.kefu_work_time,workTime))
    }

    /**
     * 设置客服联系方式列表
     */
    override fun showCedContactList(list: ArrayList<JSONObject>) {
        contactAdapter?.data = list
    }

    /**
     * 是否显示清除数据按钮
     */
    override fun showCedClearUserDataButton(isShow: Boolean) {
        if (isShow){
            _binding?.clearDataLayout?.visibility = View.VISIBLE
        } else {
            _binding?.clearDataLayout?.visibility = View.GONE
        }
    }

    /**
     * 清除用户数据成功
     */
    override fun showCedClearUserDataSuccess() {
        //移除已登录状态
        SharedHelper.onCedLoginOut()
        Handler(Looper.getMainLooper()).postDelayed({
            onIntent(CedUserLoginAct::class.java)
        },300)
    }

    /**
     * 清除用户数据提示
     */
    private fun showCedClearUserDataDialog(){
        val dialog = ClearDataDialog(context,"User Center Page",object : ClearDataDialog.IDialogCallback{
            override fun onClick(view: View?) {
                mvpPresenter?.checkClearUserDataAction(false)
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
    }

    /**
     * 打分dialog
     */
    override fun showCedRateUsDialog(data: JSONObject) {
        ScoreDialogHelper.showStarDialog(requireContext(),data,false)
    }

    /**
     * 更新总流程完成
     */
    @Subscribe(threadMode = ThreadMode.POSTING)
    public fun onRefreshProcessCompleted(event: String){
        LogHelper.e("process refresh success >>>>>>>>>>")
        when(event){
            CedEventType.NOTICE.CED_PROCESS_REFRESHED -> {//总流程刷新完成
                //是否显示清除数据按钮
                mvpPresenter?.checkClearUserDataAction(true)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_USER_END,"")
        EventBus.getDefault().unregister(this)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}